package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constants.RedisConstants;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-11-10
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LikedRecordRedisServiceImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private final RabbitMqHelper rabbitMqHelper;
    private final StringRedisTemplate redisTemplate;

    /**
     * 点赞或取消点赞
     * @param recordDTO //点赞记录表单实体
     */
    @Override
    public void addLikeRecord(LikeRecordFormDTO recordDTO) {
        //1.获取当前登录用户
        Long userId = UserContext.getUser();
        //2.判断是否点赞 dto.liked 为true 则是点赞
        log.info("点赞/取消赞成功1111");
        boolean success = recordDTO.getLiked() ? liked(recordDTO,userId) : unliked(recordDTO,userId);
        if (!success){ //点赞成功或者失败时，flag为false，直接返回
            return;
        }
        log.info("点赞/取消赞成功2222");
        /*//3.统计该业务Id的总点赞数
        Integer totalLikesNum = this.lambdaQuery()
                .eq(LikedRecord::getBizId, recordDTO.getBizId())
                .count();*/
        //3.用redis统计总点赞数
        String key = RedisConstants.LIKES_BIZ_KEY_PREFIX + recordDTO.getBizId();
        Long totalLikesNum = redisTemplate.opsForSet().size(key); //调用size方法返回指定键(key)对应的集合的大小 底层是scard命令
        if (totalLikesNum == null){
            return;
        }
        //4.采用 zset结构存储点赞记录  likes_times:type : QA   likes_times:type : NOTE
        String bizTypeTotalLikeKey = RedisConstants.LIKES_TIMES_KEY_PREFIX + recordDTO.getBizType();
        redisTemplate.opsForZSet().add(bizTypeTotalLikeKey,
                recordDTO.getBizId().toString(),
                totalLikesNum);
        /*//4.发送消息到mq
        String routingKey = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, recordDTO.getBizType());
        LikedTimesDTO msg = LikedTimesDTO.of(recordDTO.getBizId(), totalLikesNum); //消息体
        log.debug("发送点赞消息 消息内容：{}",msg);
        rabbitMqHelper.send(
                MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                routingKey,
                msg);*/
    }

    /**
     * 批量查询业务点赞状态
     * @param bizIds
     * @return
     */
    @Override
    public Set<Long> isBizLiked(List<Long> bizIds) {
        /*//1.获取当前登录用户id
        Long userId = UserContext.getUser();
        //2.循环bizIds
        Set<Long> likedBizIds = new HashSet<>();
        for (Long bizId : bizIds) {
            //判断该业务id  点赞集合中是否包含当前用户
            Boolean member = redisTemplate.opsForSet().isMember(RedisConstants.LIKE_BIZ_KEY_PREFIX + bizId, userId.toString());

            if (member){
                likedBizIds.add(bizId);
            }
        }
        *//*if (bizIds == null || bizIds.size() == 0){
            return CollUtils.emptySet();
        }
        //1.获取当前登录用户
        Long userId = UserContext.getUser();
        //2.查询点赞记录表
        List<LikedRecord> list = lambdaQuery()
                .in(LikedRecord::getBizId, bizIds)
                .eq(LikedRecord::getUserId, userId)
                .list();
        //3.查寻到的 bizid转集合
        Set<Long> likedBizIds = list.stream().map(LikedRecord::getBizId).collect(Collectors.toSet());*//*
        return likedBizIds;*/

        // 1.获取登录用户id
        Long userId = UserContext.getUser();
        // 2.查询点赞状态  开启管道模式Pipeline
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                String key = RedisConstants.LIKES_BIZ_KEY_PREFIX + bizId;
                src.sIsMember(key, userId.toString()); //判断用户是否点赞 SISMEMBER bizId userId
            }
            return null;
        });
        // 3.返回结果
        return IntStream.range(0, objects.size()) // 创建从0到集合size的流
                .filter(i -> (boolean) objects.get(i)) // 遍历每个元素，保留结果为true的角标i
                .mapToObj(bizIds::get) // 用角标i取 bizIds中的对应数据，就是点赞过的id
                .collect(Collectors.toSet());// 收集
    }

    //取消点赞
    private boolean unliked(LikeRecordFormDTO recordDTO, Long userId) {
        //1.获取Key likes:set:biz: 点赞业务id
        String key = RedisConstants.LIKES_BIZ_KEY_PREFIX + recordDTO.getBizId();
        //2.执行SREM命令
        Long result = redisTemplate.opsForSet().remove(key, userId.toString());
        return result != null && result > 0;
        /*//1.判断是否已经点赞
        LikedRecord record = this.lambdaQuery()
                .eq(LikedRecord::getUserId, userId)
                .eq(LikedRecord::getBizId, recordDTO.getBizId())
                .one();
        if (record == null){
            //未点赞
            return false;
        }
        //删除点赞记录
        boolean result = this.removeById(record.getId());
        return result;*/
    }

    //点赞
    private boolean liked(LikeRecordFormDTO recordDTO, Long userId) {
        //1.基于redis做点赞
        //拼接key  likes:set:biz: 点赞业务id
        String key = RedisConstants.LIKES_BIZ_KEY_PREFIX + recordDTO.getBizId();
        //在redis的set中添加点赞记录
        Long result = redisTemplate.opsForSet().add(key, userId.toString());//如果集合中不存在userId则添加，成功返回1，如果有userId则添加失败，返回0
        return result !=null && result > 0;
        /*//1.判断是否已经点赞
        LikedRecord record = this.lambdaQuery()
                .eq(LikedRecord::getUserId, userId)
                .eq(LikedRecord::getBizId, recordDTO.getBizId())
                .one();
        if (record != null){
            //已经点赞
            return false;
        }
        //保存点赞记录
        LikedRecord likedRecord = new LikedRecord();
        likedRecord.setUserId(userId);
        likedRecord.setBizId(recordDTO.getBizId());
        likedRecord.setBizType(recordDTO.getBizType());

        boolean result = this.save(likedRecord);
        return result;*/
    }

    /**
     * 定时任务，每隔20s，查询业务点赞次数，发送消息到mq
     * @param bizType
     * @param maxBizSize
     */
    @Override
    public void readLikedTimesAndSendMessage(String bizType, int maxBizSize) {
        //1.拼接key likes:times:type : QA  likes:times:type : NOTE
        String bizTypeTotalLikeKey = RedisConstants.LIKES_TIMES_KEY_PREFIX + bizType;

        List<LikedTimesDTO> list = new ArrayList<>();
        //2.从redis的zset集合中，按照分数排序，取出前maxBizSize 的业务点赞信息  popmin 删除并返回
        Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().popMin(bizTypeTotalLikeKey, maxBizSize);
        if (CollUtils.isEmpty(typedTuples)){
            return;
        }
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String bizId = typedTuple.getValue();
            Double likeTimes = typedTuple.getScore();
            if (StringUtils.isBlank(bizId) || likeTimes == null){
                continue;
            }
            //3.封装LikedDTO   消息数据
            LikedTimesDTO msg = LikedTimesDTO.of(Long.valueOf(bizId), likeTimes.intValue());
            list.add(msg);
        }

        //4.发送消息到mq
        //  “QA.times.changed”
        String routingKey = StringUtils.format(MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE, bizType);

        if (CollUtils.isNotEmpty(list)){
            log.debug("批量发送点赞消息 消息内容：{}",list);
            rabbitMqHelper.send(
                    MqConstants.Exchange.LIKE_RECORD_EXCHANGE,
                    routingKey,
                    list);
        }
    }
}
